import 'dart:async';

import 'package:enjoy_plus/utils/event_bus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 倒计时初始时间
  int _countdown = 60;
  // 是否正在倒计时
  bool _isCountingDown = false;
  // 计时器
  Timer? _timer;
  // 手机号输入框控制器
  final _phoneController = TextEditingController();
  // 验证码输入框控制器
  final _codeController = TextEditingController();
  // 倒计时
  void _startCountdown() async {
    if (_isCountingDown) return;
    _isCountingDown = true;
    final res =
        await http.get('/code', params: {'mobile': _phoneController.text});
    if (res['code'] != 10000) {
      return ToastUtil.showError('验证码获取失败');
    }
    ToastUtil.showSuccess('验证码获取成功');
    _codeController.text = res['data']['code'];
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 1) {
          _countdown--;
        } else {
          _countdown = 60;
          _isCountingDown = false;
          _timer?.cancel();
        }
      });
    });
  }

// 获取验证码
  _verifyCode() {
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }
    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }
    _startCountdown();
  }

  _login() async {
    // 判断手机号
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }
    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }
    // 判断验证码
    if (_codeController.text.isEmpty) {
      return ToastUtil.showError('请输入验证码');
    }
    RegExp regExp1 = RegExp(r'^\d{6}$');
    if (!regExp1.hasMatch(_codeController.text)) {
      return ToastUtil.showError('请输入正确的验证码');
    }
    // 发送请求
    final res = await http.post('/login', {
      'mobile': _phoneController.text,
      'code': _codeController.text,
    });
    if (res['code'] != 10000) {
      return ToastUtil.showError('登录失败');
    }
    ToastUtil.showSuccess('登录成功');
    final tokenManager = TokenManager();
    tokenManager.setToken(res['data']['token']);
    // 清除倒计时
    _timer?.cancel();
    eventBus.fire(RefreshMine());
    // 跳转到主页
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: TextField(
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                      controller: _phoneController,
                      maxLength: 11,
                      keyboardType: TextInputType.phone,
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        shadowColor: Colors.transparent,
                        foregroundColor:
                            const Color.fromARGB(255, 85, 145, 175),
                        minimumSize: const Size(100, 50)),
                    onPressed: () {
                      // _startCountdown();
                      _verifyCode();
                    },
                    child: _isCountingDown
                        ? Text(
                            '$_countdown s后重新获取',
                            style: const TextStyle(color: Colors.grey),
                          )
                        : const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
                controller: _codeController,
                maxLength: 6,
                keyboardType: TextInputType.number,
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(children: [
                Expanded(
                    child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _login();
                  },
                  child: const Text('登录',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ))
              ])
            ])));
  }
}
